package com.cn.pack.service;

import com.cn.pack.po.Animal;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCollapser;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;

@Service
public class CollapsingService {

    private List<Animal> animalList;

    @HystrixCollapser(
            batchMethod = "collapsingList",
            scope = com.netflix.hystrix.HystrixCollapser.Scope.GLOBAL,
            collapserProperties = {@HystrixProperty(name = "timerDelayInMilliseconds", value = "1000")}
    )
    public Future<Animal> collapsing(Integer id) {
        return null;
    }

    @HystrixCommand(fallbackMethod = "fallback")
    public List<Animal> collapsingList(List<Integer> animalParam) throws Exception {
        System.out.println("collapsingList当前线程" + Thread.currentThread().getName());
        System.out.println("当前请求参数个数：" + animalParam.size());
        animalList = new ArrayList<>();

        //返回的结果数量必须与请求的数量一致，所以预先放置一定数量的结果
        for (int i = 0; i < animalParam.size(); i++) {
            animalList.add(null);
        }

        for (int i = 0; i < animalParam.size(); i++) {
            Integer id = animalParam.get(i);
            System.out.println("id = " + id);
            if (id.compareTo(122) == 0) {
                throw new Exception();
            }
            Animal animal = new Animal();
            animal.setName("Dog" + id);
            animal.setAge(id);
            animalList.set(i, animal);
        }

        return animalList;
    }

    public List<Animal> fallback(List<Integer> animalParam) throws Exception {
        System.out.println("ERROR -- animalParam = " + animalParam.toString());
        for (Animal animal : animalList) {
            System.out.println("ERROR -- Animal = " + animal);
        }
        System.out.println("ERROR -- animalListSize = " + animalList.size());
        return animalList;
    }
}
